#!/usr/bin/env python
# coding=utf-8

from string import Template
from optparse import OptionParser

def main():
    binpathtpl = '/usr/bin/{}'
    paramtpl = '-c /etc/{}.conf'
    name = 'demo'
    binpath = binpathtpl.format(name)
    param = paramtpl.format(name)
    workdir = '/'
    user = 'root'
    usage = '%prog [options]'
    parser = OptionParser(usage = usage)
    parser.add_option('-n', '--name', type='string', dest='name', help=u'name option', metavar=name)
    parser.add_option('-b', '--bin', type='string', dest='bin', help=u'bin option', metavar=binpath)
    parser.add_option('-p', '--param', type='string', dest='param', help=u'param option', metavar=param)
    parser.add_option('-d', '--workdir', type='string', dest='workdir', help=u'dir option', metavar=workdir)
    parser.add_option('-u', '--user', type='string', dest='user', help=u'user option', metavar=user)
    (options, args) = parser.parse_args()
    if not options.name:
        parser.print_help()
        return
    name = options.name
    if options.bin:
        binpath = options.bin
    else:
        binpath = binpathtpl.format(name)
    if options.param != None:
        param = options.param
    else:
        param = paramtpl.format(name)
    if options.workdir:
        workdir = options.workdir
    if options.user:
        user = options.user

    templateData = {
        'SERVICE_NAME': name,
        'SERVICE_PATH': binpath,
        'SERVICE_PARAM': param,
        'SERVICE_HOME': workdir,
        'SERVICE_USER': user,
        }
    print(templateData)
    templateStr = ''
    with open('./script.tpl', 'r') as rf:
        templateStr = rf.read()

    template = Template(templateStr)
    content = template.safe_substitute(templateData)

    with open('./script', 'w') as wf:
        wf.write(content)

if __name__ == "__main__":
    main()

